import type { ValidationRule } from 'ant-design-vue/lib/form/Form';
import type { RuleObject } from 'ant-design-vue/lib/form/interface';
import { ref, computed, unref, Ref } from 'vue';

// 登录模式对应的枚举状态
export enum LoginStateEnum {
  LOGIN,
  REGISTER,
  RESET_PASSWORD,
  MOBILE,
  QR_CODE,
}

// 创建一个响应式 登录模式状态
const currentState = ref(LoginStateEnum.LOGIN);

export function useLoginState() {
  function setLoginState(state: LoginStateEnum) {
    currentState.value = state;
  }

  // 根据它的返回值 与 枚举类型做对比 确定当前展示每个登录模式
  const getLoginState = computed(() => currentState.value);

  // 点击返回按钮 变成默认登录模式 LoginStateEnum.LOGIN = 0
  function handleBackLogin() {
    setLoginState(LoginStateEnum.LOGIN);
  }

  return { setLoginState, getLoginState, handleBackLogin };
}

export function useFormValid<T extends Object = any>(formRef: Ref<any>) {
  async function validForm() {
    const form = unref(formRef);
    if (!form) return;
    const data = await form.validate();
    return data as T;
  }

  return { validForm };
}

export function useFormRules(formData?: Recordable) {
  // 注册时校验当前是否勾选了同意隐私政策
  const validatePolicy = async (_: RuleObject, value: boolean) => {
    return !value ? Promise.reject('勾选后才能注册') : Promise.resolve();
  };

  const validateConfirmPassword = (password: string) => {
    return async (_: RuleObject, value: string) => {
      if (!value) {
        return Promise.reject('请输入密码');
      }
      if (value !== password) {
        return Promise.reject('两次输入密码不一致');
      }
      return Promise.resolve();
    };
  };

  const getFormRules = computed((): { [k: string]: ValidationRule | ValidationRule[] } => {
    const accountFormRule = createRule('请输入账号');
    const passwordFormRule = createRule('请输入密码');

    const mobileFormRule = createRule('请输入手机号码');
    const smsFormRule = createRule('请输入验证码');

    // 手机登录规则
    const mobileRule = {
      mobile: mobileFormRule,
      sms: smsFormRule,
    };
    // 根据选择的登录模式 返回对应的校验信息
    switch (unref(currentState) as LoginStateEnum) {
      // 注册
      case LoginStateEnum.REGISTER:
        return {
          account: accountFormRule,
          password: passwordFormRule,
          confirmPassword: [
            { validator: validateConfirmPassword(formData?.password), trigger: 'change' },
          ],
          // 同意隐私政策
          policy: [{ validator: validatePolicy, trigger: 'change' }],
          ...mobileRule,
        };

      // 忘记密码
      case LoginStateEnum.RESET_PASSWORD:
        return {
          account: accountFormRule,
          ...mobileRule,
        };

      case LoginStateEnum.MOBILE:
        return mobileRule;

      // 默认登录 账号密码
      default:
        return {
          account: accountFormRule,
          password: passwordFormRule,
        };
    }
  });
  return { getFormRules };
}

function createRule(message: string) {
  return [
    {
      required: true,
      message,
      trigger: 'change',
    },
  ];
}
